var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Category = require('../models/category');
var Post = require('../models/post');
var User = require('../models/user');
var Collect = require('../models/collect');
var Focus = require('../models/focus');
var pageHelper = require('../helper/page');


// 用户中心
router.get('/', function (req, res, next) { 
	res.render('user', {
	  title: '机械社区-机械从业者交流中心'
	});
});  


// 修改用户名
router.get('/edit', function (req, res, next) { 
	res.render('edit', {
	  title: '修改账户信息'
	});
});



// 添加用户名
router.post('/add', function (req, res, next) { 
  var name = req.body.username,openid = req.session.user.openid;
  if (!openid) return next(new Error('请先授权！'))
  User.getUser(openid, function (err, user) {
    if (err) return next(err);
    if (user.username == name) {
      res.json({'result': 0});
    } else {
      // 根据id修改用户名 并返回最新
      User.findByIdAndUpdate(user._id, { $set: { 'username': name }}, {new: true}, function (err, newUser) {
          if (err) return handleError(err);
          req.session.user = newUser;
          res.json({'result': 1});
      });
    }
  });
});


// 收藏列表
router.get('/collects', function (req, res, next) { 
  res.render('collect',{
    title: '我的收藏'
  });
});

router.get('/collects/list', function (req, res, next) { 
  var opts = [
    {
      path: 'post.category',
      // select: 'name',
      model: 'Category'
    },
    {
      path: 'post.author',
      model: 'User'      
    }
  ];
	var page = req.query.page || 1;
	pageHelper.pageQueryMoreModel(page,6,Collect,['post'],{'userid':req.session.user._id},{created: 'desc'},opts, function (err, $page){
		if (err) {
		  return next(err);
		} else {
		  res.jsonp($page);
		}
	});
  // 多表关联查询demo
  // Collect.find({'userid':req.session.user._id}).populate('post').exec(function (err, docs) {
  //   var opt = [{
  //     path: 'post.category',
  //     select: 'name',
  //     model: 'Category'
  //   }];
  //   Collect.populate(docs, opt, function (err, populatedDocs) {
  //     console.log(populatedDocs);
  //     res.jsonp(populatedDocs);
  //   });
  // });
});

// 关注列表
router.get('/focus', function (req, res, next) { 
  res.render('focus',{
    title: '我的关注'
  });
});

router.get('/focus/list', function (req, res, next) { 
  var page = req.query.page || 1;
  pageHelper.pageQuery(page,6,Focus,['touser'],{userid:req.session.user._id},{created: 'desc'}, function (err, $page){
    if (err) {
      return next(err);
    } else {
      res.jsonp($page);
    }
  });
});


// 进入某人发表过的文章显示页
router.get('/:userId/article', function(req, res, next) {
  User.findOne({_id:req.params.userId}).exec(function (err, user) {
    if (err) return next(err);
    res.render('userPost',{
      title: user.username+'的文章',
      userid: user._id
    });
  });
});

// GET /user/:userid/article  查看某人发表过的文章
router.get('/:userId/article/list', function(req, res, next) {
  var userId = req.params.userId;
  var page = req.query.page || 1;
  pageHelper.pageQuery(page,10,Post,['author','category'],{'authorId':'584af8add78b2f6a87ae4f01'},{created: 'desc'}, function (err, $page){
    if (err) {
      return next(err);
    } else {
      res.jsonp($page);
    }
  });


});



// GET /user/:touserId/focus  查看当用户是否关注了作者
router.get('/:touserId/focus', function (req, res, next) { 
  var touserId = req.params.touserId;
  if (!touserId) return next(new Error('no focusId in app'));
  Focus.findOne({'userid':req.session.user._id, "touser": touserId }, function (err, focus) {
      if (err) return next(err);
      // 没有关注
      if (focus == null) {
        res.jsonp({'result':0});
      }
      // 已关注
      else {
        res.jsonp({'result':1});
      }
  });
});

// GET /user/:touserId/focus/add  针对用户新增关注
router.get('/:touserId/focus/add', function (req, res, next) { 
  var touserId = req.params.touserId;
  if (!touserId) return next(new Error('no touserId in app'));
  var focus =  new Focus({
    'userid': req.session.user._id,
    'touser': touserId,
    'create_at': new Date()
  });
  // 保存关注
  var promise = focus.save();
  promise.then(function (focus) {
    // 关注成功
    res.jsonp({'result':1});
  })
  .catch(function (err) {
    if (err) return next(err);
  });
});

// GET /user/:touserId/focus/del  针对用户取消关注
router.get('/:touserId/focus/del', function (req, res, next) { 
  var touserId = req.params.touserId;
  if (!touserId) return next(new Error('no focusId in app'));
  Focus.remove({userid: req.session.user._id, touser: touserId}).exec(function (err) {
    if (err) return next(err);
    res.jsonp({'result':1});      
  });
});


module.exports = router;
